package com.baozi.order.controller;

import com.baozi.order.converter.OrderFrom2OrderDto;
import com.baozi.order.dto.OrderDto;
import com.baozi.order.enums.ResultEnum;
import com.baozi.order.exception.OrderException;
import com.baozi.order.from.OrderFrom;
import com.baozi.order.service.OrderService;
import com.baozi.order.utlis.ResultVoUtil;
import com.baozi.order.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;

    @RequestMapping("add")
    public ResultVo<Map<String,String>> add(@Valid OrderFrom orderFrom, BindingResult bindingResult) {
        if(bindingResult.hasErrors()){
            log.info("参数不对={}",orderFrom);
            throw new OrderException(ResultEnum.PARAM_ERROR.getCode(),bindingResult.getFieldError().getDefaultMessage());
        }
        OrderDto orderDto=OrderFrom2OrderDto.convert(orderFrom);
        if(CollectionUtils.isEmpty(orderDto.getList())){
            log.info("购物车信息空={}",orderDto.getList());
            throw new OrderException(ResultEnum.CART_ERROR);
        }
        OrderDto result=orderService.add(orderDto);
        Map<String,String> map=new HashMap<>();
        map.put("orderId",result.getOrderId());
      return  ResultVoUtil.success(map);
    }
}
